package main.api;

import main.*;
import main.cipher.TokenUtils;
import main.database.AccountHelper;
import org.json.JSONObject;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Map;

@RestController
public class MailApi {
    @PostMapping("/api/mailsend")
    public ResponseEntity<?> mailSend(HttpServletRequest request) {
        String toAccount = null;
        Map<String, String[]> map = request.getParameterMap();
        if (map.containsKey("email")) {
            toAccount = map.get("email")[0];
        }

        String uuid = RequestHelper.getUserUUIDFromRequest(request);

        String result;
        if (toAccount == null || toAccount.isEmpty()) {
            result = ResponseHelper.createBasicJsonObject(404, "没有提供邮箱").toString();
        }
        else if (uuid == null) {
            result = ResponseHelper.createBasicJsonObject(404, "没有登录").toString();
        }
        else if (!AccountHelper.isExistFromUUID(uuid)) {
            result = ResponseHelper.createBasicJsonObject(404, "登录的用户不存在").toString();
        }
        else if (MailHelper.isEmailAlreadyExist(toAccount)) {
            result = ResponseHelper.createBasicJsonObject(404, "该邮箱已经被使用").toString();
        }
        else {
            String title = GlobalConfig.siteName + "邮箱绑定确认";
            String now = new Timestamp(new Date().getTime()).toString();
            JSONObject jo = new JSONObject();
            jo.put("time", now);
            jo.put("mail", toAccount);
            jo.put("uuid", uuid);
            jo.put("random", StringHelper.getAlphaNumericString(16));
            String param = jo.toString();
            param = TokenUtils.encrypt(param);

            String nickName = AccountHelper.getAccountInfoFromUUID(uuid);
            String content = makeBindContent(param, nickName);
            MailHelper.sendMail(GlobalConfig.siteName, GlobalConfig.mailSender, GlobalConfig.mailSenderPwd, toAccount, title, content);

            result = ResponseHelper.createBasicJsonObject(200, "ok").toString();
        }

        return ResponseEntity.ok(result);
    }

    @PostMapping("/api/mailsendtofindpassword")
    public ResponseEntity<?> mailSendToFindPassword(HttpServletRequest request, ModelMap modelMap) {
        String toAccount = null;
        Map<String, String[]> map = request.getParameterMap();
        if (map.containsKey("email")) {
            toAccount = map.get("email")[0];
        }

        String result;
        if (toAccount == null || toAccount.isEmpty()) {
            result = ResponseHelper.createBasicJsonObject(404, "没有提供邮箱").toString();
        }
        else if (!AccountHelper.isExistFromEmail(toAccount)) {
            result = ResponseHelper.createBasicJsonObject(404, "提供的邮箱地址在网站内不存在").toString();
        }
        else {
            String title = GlobalConfig.siteName + "账号找回";
            String now = new Timestamp(new Date().getTime()).toString();
            JSONObject jo = new JSONObject();
            jo.put("time", now);
            jo.put("mail", toAccount);
            jo.put("random", StringHelper.getAlphaNumericString(16));
            String param = jo.toString();
            param = TokenUtils.encrypt(param);

            String content = makeFindPasswordContent(param);
            MailHelper.sendMail(GlobalConfig.siteName, GlobalConfig.mailSender, GlobalConfig.mailSenderPwd, toAccount, title, content);

            result = ResponseHelper.createBasicJsonObject(200, "ok").toString();
        }

        return ResponseEntity.ok(result);
    }

    private String makeBindContent(String param, String nickName) {
        String url = null;

        try {
            url = GlobalConfig.siteUrl + GlobalConfig.bindEmailUrl + URLEncoder.encode(param, "UTF-8");
        }
        catch (UnsupportedEncodingException e) {
            Logman.error(e.getStackTrace().toString());
        }

        StringBuilder stringBuilder = new StringBuilder("尊敬的");
        stringBuilder.append(GlobalConfig.siteName);
        stringBuilder.append("用户：");
        stringBuilder.append("\n");
        stringBuilder.append("\t您在我们网站发起邮箱绑定(绑定昵称：");
        stringBuilder.append(nickName);
        stringBuilder.append(")，这里是绑定链接（前后无空格）：");
        stringBuilder.append("\n");
        stringBuilder.append("            ");
        stringBuilder.append(url);
        stringBuilder.append("            ");
        stringBuilder.append("\n");
        stringBuilder.append("\n");
        stringBuilder.append("如果绑定链接无法点击，请复制到浏览器地址栏，再直接访问。如果绑定非您发起，请忽略。");

        return stringBuilder.toString();
    }

    private String makeFindPasswordContent(String param) {
        String url = null;

        try {
            url = GlobalConfig.siteUrl + GlobalConfig.findPasswordUrl + URLEncoder.encode(param, "UTF-8");
        }
        catch (UnsupportedEncodingException e) {
            Logman.error(e.getStackTrace().toString());
        }

        StringBuilder stringBuilder = new StringBuilder("尊敬的");
        stringBuilder.append(GlobalConfig.siteName);
        stringBuilder.append("用户：");
        stringBuilder.append("\n");
        stringBuilder.append("\t您在我们网站发起通过邮箱重置密码，这里是重置链接（2小时内有效，前后无空格）：");
        stringBuilder.append("\n");
        stringBuilder.append("    ");
        stringBuilder.append(url);
        stringBuilder.append("    ");
        stringBuilder.append("\n");
        stringBuilder.append("\n");
        stringBuilder.append("如果重置链接无法点击，请复制到浏览器地址栏，再直接访问。如果重置非您发起，请注意账号安全或者忽略。");

        return stringBuilder.toString();
    }
}
